package com.ml.room.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ml.room.common.constant.RedisConstant;
import com.ml.room.common.result.CommonResult;
import com.ml.room.common.utils.RedisOperateUtil;
import com.ml.room.dao.IBuildingProjectDao;
import com.ml.room.dao.IBuildingProjectItemDao;
import com.ml.room.dao.IBuildingRecordDao;
import com.ml.room.repository.dto.BuildingRecordDto;
import com.ml.room.repository.entity.BuildingProject;
import com.ml.room.repository.entity.BuildingProjectItem;
import com.ml.room.repository.entity.BuildingRecord;
import com.ml.room.service.IBuildingRecordService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @ClassName: IBuildingRecordServiceImpl
 * @Decription: 此处填写类文件说明
 * @Author: IDai
 * @Date: 2021-08-13 14:48 星期五
 **/
@Service
public class IBuildingRecordServiceImpl extends ServiceImpl<IBuildingRecordDao, BuildingRecord> implements IBuildingRecordService {
    @Autowired
    private IBuildingRecordDao buildingRecordDao;
    @Autowired
    private IBuildingProjectDao buildingProjectDao;
    @Autowired
    private IBuildingProjectItemDao buildingProjectItemDao;
    @Autowired
    private RedisOperateUtil redisOperateUtil;

    /** 日志打印工具 **/
    private static final Logger logger = LoggerFactory.getLogger(IBuildingRecordServiceImpl.class);

    @Override
    public IPage<BuildingRecord> selectNotCollarList(Map<String, String> collarMap) {
        logger.info("【合肥新房】 - 房屋备案 - 查询未抓取的数据列表 - 入参collarMap：{}", JSON.toJSONString(collarMap));
        LambdaQueryWrapper<BuildingRecord> queryWrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotBlank(collarMap.get("infoStatus"))){
            queryWrapper.eq(BuildingRecord::getInfoStatus, Integer.parseInt(collarMap.get("infoStatus")));
        }
        if (StringUtils.isNotBlank(collarMap.get("projectStatus"))){
            queryWrapper.eq(BuildingRecord::getProjectStatus, Integer.parseInt(collarMap.get("projectStatus")));
        }
        IPage<BuildingRecord> pageParam = new Page<>();
        pageParam.setPages(1);
        pageParam.setSize(100);
        IPage<BuildingRecord> pageList = buildingRecordDao.selectPage(pageParam, queryWrapper);
        logger.info("【合肥新房】 - 房屋备案 - 查询未抓取的数据列表 - 出参collarMap：{}", JSON.toJSONString(pageList));
        return pageList;
    }

    @Override
    public BuildingRecord findBuildingRecordInfo(String remarkNo) {
        LambdaQueryWrapper<BuildingRecord> RecordQueryWrapper = new LambdaQueryWrapper<>();
        RecordQueryWrapper.eq(BuildingRecord::getRemarkNo, remarkNo);
        BuildingRecord buildingRecord = buildingRecordDao.selectOne(RecordQueryWrapper);
        LambdaQueryWrapper<BuildingProject> projectQueryWrapper = new LambdaQueryWrapper<>();
        projectQueryWrapper.eq(BuildingProject::getRecordId, buildingRecord.getId());
        BuildingProject buildingProject = buildingProjectDao.selectOne(projectQueryWrapper);
        buildingRecord.setBuildingProject(buildingProject);
        LambdaQueryWrapper<BuildingProjectItem> projectItemQueryWrapper = new LambdaQueryWrapper<>();
        projectItemQueryWrapper.eq(BuildingProjectItem::getRecordId, buildingRecord.getId());
        List<BuildingProjectItem> projectItems = buildingProjectItemDao.selectList(projectItemQueryWrapper);
        buildingRecord.setProjectItems(projectItems);
        return buildingRecord;
    }

    @Override
    public CommonResult<IPage<BuildingRecord>> selectBuildingList(BuildingRecordDto buildingRecordDto) {
        logger.info("[热门搜索] - 根据楼盘名称模糊分页查询楼盘列表 - 入参buildingRecordDto：{}", JSON.toJSONString(buildingRecordDto));
        IPage<BuildingRecord> iPage = new Page<>();
        iPage.setCurrent(buildingRecordDto.getPage());
        iPage.setSize(buildingRecordDto.getSize());
        LambdaQueryWrapper<BuildingRecord> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.like(BuildingRecord::getBuildingName, buildingRecordDto.getBuildingName());
        IPage<BuildingRecord> page = buildingRecordDao.selectPage(iPage, lambdaQueryWrapper);
        return CommonResult.success(page);
    }

    @Override
    public CommonResult<?> selectHotSearch() {
        logger.info("[热门搜索] - 查询楼盘热搜数据 - 入参：{}", "无");
        CommonResult<?> commonResult = CommonResult.failed("系统异常，请联系管理员！");
        //从 redis 中根据 热度 score分数倒序查出10条热搜词
        Set<String> hotSearchSet = redisOperateUtil.zReverseRange(RedisConstant.BUILDING_HOT_SEARCH_KEY + "安徽省合肥市", 0, 9);
        if (CollectionUtil.isNotEmpty(hotSearchSet)){
            commonResult = CommonResult.success(hotSearchSet);
        }
        logger.info("[热门搜索] - 查询楼盘热搜数据 - 出参commonResult：{}", JSON.toJSONString(commonResult));
        return null;
    }

    @Override
    public CommonResult<?> selectHotSearchBuildingRecords() {
        logger.info("[热门搜索] - 程序[IBuildingRecordServiceImpl.selectHotSearchBuildingRecords]开始运行 - 查询热搜楼盘 - 入参：{}", "无");
        CommonResult<?> commonResult = CommonResult.failed("系统异常，请联系管理员！");
        //从 redis 中根据 热度 score分数倒序查出10条热搜词
        Set<String> hotSearchSet = redisOperateUtil.zReverseRange(RedisConstant.BUILDING_HOT_SEARCH_KEY + "安徽省合肥市", 0, 9);
        if (CollectionUtil.isNotEmpty(hotSearchSet)){
            LambdaQueryWrapper<BuildingRecord> buildingQueryWrapper = new LambdaQueryWrapper<>();
            buildingQueryWrapper.in(BuildingRecord::getBuildingName, hotSearchSet);
            //查询热门楼盘数据
            List<BuildingRecord> buildingRecords = buildingRecordDao.selectList(buildingQueryWrapper);
            if (CollectionUtil.isNotEmpty(buildingRecords)){
                buildingRecords.stream().forEach(buildingRecord -> {
                    buildingRecord.setBuildingProject(buildingProjectDao.selectOneByRecordId(buildingRecord.getId()));
                });
                commonResult = CommonResult.success(buildingRecords);
            }
        }
        logger.info("[热门搜索] - 程序[IBuildingRecordServiceImpl.selectHotSearchBuildingRecords]结束运行 - 返回热搜楼盘 - 入参：{}", JSON.toJSONString(commonResult));
        return commonResult;
    }

    @Override
    public CommonResult<?> findBuildingGlobalInfo(Map<String, Object> searchMap) {
        logger.info("[楼盘大致信息] - 根据楼盘名称查询楼盘详情大致信息 - 入参：{}", JSON.toJSONString(searchMap));
        CommonResult<?> commonResult = CommonResult.failed("系统异常，请联系管理员！");
        String buildingName = (String) searchMap.get("buildingName");
        LambdaQueryWrapper<BuildingRecord> buildingQueryWrapper = new LambdaQueryWrapper<>();
        buildingQueryWrapper.eq(BuildingRecord::getBuildingName, buildingName);
        List<BuildingRecord> buildingRecords = buildingRecordDao.selectList(buildingQueryWrapper);
        if (CollectionUtil.isNotEmpty(buildingRecords)){
            //首先，先判断热搜缓存中是否有此楼盘
            if (!redisOperateUtil.hasKey(RedisConstant.BUILDING_HOT_SEARCH_KEY + "安徽省合肥市")){
                //然后，如果热搜缓存中无此热词，则加入
                redisOperateUtil.zAdd(RedisConstant.BUILDING_HOT_SEARCH_KEY + "安徽省合肥市", buildingName, 1);
            }
            //则新增热度值。
            redisOperateUtil.zIncrementScore(RedisConstant.BUILDING_HOT_SEARCH_KEY + "安徽省合肥市", buildingName,1);
            commonResult = CommonResult.success(buildingRecords);
        }
        logger.info("[楼盘大致信息] - 根据楼盘名称查询楼盘详情大致信息 - 返回结果 - 入参：{}", JSON.toJSONString(commonResult));
        return commonResult;
    }


}
